<template>
	<view class="edit-resign-page">
		<u-navbar
			title="编辑"
			:border="false"
			:auto-back="true"
			:bg-color="'#FFFFFF'"
			:title-color="'#333333'"
			:title-size="36"
			:title-weight="'bold'"
			placeholder
		>
		</u-navbar>

		<view class="form-content">
			<view class="form-section">
				<view class="section-header">
					<text class="section-title">计划离职</text>
				</view>
				<view class="form-field">
					<text class="field-label required">日期</text>
					<view class="select-field" @click="openDatePicker">
						<text class="select-text">{{ formData.planDate || '请选择日期' }}</text>
						<text class="select-arrow">›</text>
					</view>
				</view>
			</view>

			<view class="form-section">
				<view class="section-header">
					<text class="section-title">离职类型</text>
				</view>
				<view class="form-field">
					<text class="field-label required">类型</text>
					<view class="select-field" @click="openTypePicker">
						<text class="select-text">{{ formData.regularWorkTypeName || '请选择离职类型' }}</text>
						<text class="select-arrow">›</text>
					</view>
				</view>
			</view>

			<view class="form-section">
				<view class="section-header">
					<text class="section-title">离职原因</text>
				</view>
				<u-input
					v-model="formData.regularReason"
					placeholder="请输入"
					type="textarea"
					:maxlength="500"
					:show-count="true"
					:auto-height="true"
					:border="false"
					:custom-style="{ padding: '20rpx', backgroundColor: '#FFFFFF', borderRadius: '8rpx', border: '1rpx solid #E0E0E0' }"
				/>
			</view>

			<!-- 图片上传 -->
			<view class="form-section">
				<view class="section-header">
					<text class="section-title">图片附件</text>
				</view>
				<view class="upload-area">
					<view v-if="formData.attachments.length === 0" class="no-attachments">
						<text class="no-attachments-text">暂无附件</text>
					</view>
					<view v-else class="attachments-list">
						<view 
							v-for="(file, index) in formData.attachments" 
							:key="index"
							class="file-item"
						>
							<!-- 图片缩略图 -->
							<image 
								v-if="isImageFile(file.name)" 
								:src="getImageUrl(file)" 
								class="file-thumbnail"
								mode="aspectFill"
								@click="previewImage(file)"
							/>
							<!-- 文件图标 -->
							<view v-else class="file-icon" @click="previewFile(file)">
								<text class="icon-text">📎</text>
							</view>
							<!-- 文件信息 -->
							<view class="file-info">
								<text class="file-name">{{ file.name }}</text>
								<text class="file-size" v-if="file.fileSize">{{ formatFileSize(file.fileSize) }}</text>
							</view>
							<!-- 删除按钮 -->
							<text class="delete-file" @click.stop="deleteFile(index)">×</text>
						</view>
					</view>
					<!-- 上传按钮 -->
					<view class="upload-placeholder" @click="chooseFile">
						<text class="upload-icon">📎</text>
						<text class="upload-text">点击上传附件</text>
					</view>
				</view>
			</view>
		</view>

		<view class="bottom-actions">
			<button class="action-btn cancel-btn" @click="goBack">取消</button>
			<button class="action-btn submit-btn" @click="submitForm">确定</button>
		</view>
	</view>

	<u-datetime-picker
		:show="showDatePicker"
		mode="date"
		v-model="currentDate"
		@confirm="onDateConfirm"
		@cancel="showDatePicker = false"
		:custom-style="{ confirmColor: '#FF6B35', cancelColor: '#666666' }"
		:min-date="new Date().getTime()"
		:max-date="new Date('2030-12-31').getTime()"
		:close-on-click-overlay="false"
		:show-toolbar="true"
		:title="'选择日期'"
		:z-index="1000"
	/>

	<u-popup 
		:show="showTypePicker" 
		@close="closeTypePicker"
		mode="bottom"
		safeAreaInsetBottom
	>
		<view class="type-picker">
			<view class="picker-header">
				<text class="picker-cancel" @click="closeTypePicker">取消</text>
				<text class="picker-title">选择离职类型</text>
				<text class="picker-confirm" @click="confirmTypeSelection">确认</text>
			</view>
			<view class="picker-content">
				<view 
					v-for="(type, index) in resignTypes1" 
					:key="index"
					class="type-option"
					:class="{ 'selected': selectedTypeIndex === index }"
					@click="selectType(index)"
				>
					<text class="type-text">{{ type.label }}</text>
					<text v-if="selectedTypeIndex === index" class="type-check">✓</text>
				</view>
			</view>
		</view>
	</u-popup>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { resignApi, uploadApi } from '@/api/api-helper.js'
import { userStore } from '@/stores/userStore'

const pageParams = ref({ id: '' })
const showDatePicker = ref(false)
const showTypePicker = ref(false)
const currentDate = ref(new Date().getTime())
const selectedTypeIndex = ref(-1)

const formData = ref({
	planDate: '',
	regularWorkType: '',
	regularWorkTypeName: '',
	regularReason: '',
	attachments: []
})

const resignTypes1 = ref([
	{ value: 'activeResign', label: '主动离职' },
	{ value: 'passiveResign', label: '被动离职' },
	{ value: 'trialPeriod', label: '试用不合格' },
	{ value: 'retire', label: '退休' }
]);

onMounted(() => {
	const pages = getCurrentPages()
	const currentPage = pages[pages.length - 1]
	const options = currentPage.options || {}
	
	pageParams.value.id = options.id || ''
	
	if (pageParams.value.id) {
		loadResignDetail()
	} else {
		uni.showToast({ title: '缺少必要参数', icon: 'none' })
		setTimeout(() => { uni.navigateBack() }, 1500)
	}
})

const loadResignDetail = async () => {
	try {
		uni.showLoading({ title: '加载中...' })
		
		const response = await resignApi.getMyResignDetail(pageParams.value.id)
		if (response.code === 200) {
			const data = response.data
			formData.value = {
				planDate: data.planDate || '',
				regularWorkType: data.regularWorkType || '',
				regularWorkTypeName: data.regularWorkTypeName || '',
				regularReason: data.regularReason || '',
				attachments: []
			}
			
			// 解析附件数据
			if (data.attachments) {
				try {
					let attachmentData = data.attachments
					
					// 如果是字符串，尝试解析JSON
					if (typeof attachmentData === 'string') {
						attachmentData = JSON.parse(attachmentData)
					}
					
					console.log('解析附件数据:', attachmentData)
					
					// 处理附件数据，支持嵌套数组格式
					if (Array.isArray(attachmentData)) {
						// 如果是嵌套数组，取第一个元素
						if (attachmentData.length > 0 && Array.isArray(attachmentData[0])) {
							attachmentData = attachmentData[0]
						}
						
						// 过滤有效的附件数据
						formData.value.attachments = attachmentData.filter(item => 
							item && (item.name || item.url)
						)
					}
					
					console.log('解析后的附件数据:', formData.value.attachments)
				} catch (e) {
					console.error('解析附件数据失败:', e)
					formData.value.attachments = []
				}
			}
			
			const typeIndex = resignTypes1.value.findIndex(type => type.value === data.regularWorkType)
			if (typeIndex !== -1) {
				selectedTypeIndex.value = typeIndex
			}
		} else {
			uni.showToast({ title: response.msg || '加载失败', icon: 'none' })
		}
	} catch (error) {
		console.error('加载离职详情失败:', error)
		uni.showToast({ title: '网络错误', icon: 'none' })
	} finally {
		uni.hideLoading()
	}
}

const openDatePicker = () => { showDatePicker.value = true }
const openTypePicker = () => { showTypePicker.value = true }
const closeTypePicker = () => { showTypePicker.value = false }

const onDateConfirm = (e: any) => {
	if (e && e.value) {
		const selectedDate = new Date(e.value)
		const year = selectedDate.getFullYear()
		const month = String(selectedDate.getMonth() + 1).padStart(2, '0')
		const day = String(selectedDate.getDate()).padStart(2, '0')
		formData.value.planDate = `${year}-${month}-${day}`
	}
	showDatePicker.value = false
}

const selectType = (index: number) => { selectedTypeIndex.value = index }

const confirmTypeSelection = () => {
	if (selectedTypeIndex.value !== -1) {
		const selectedType = resignTypes1.value[selectedTypeIndex.value]
		formData.value.regularWorkType = selectedType.value
		formData.value.regularWorkTypeName = selectedType.label
	}
	closeTypePicker()
}

// 判断是否为图片文件
const isImageFile = (fileName: string) => {
	const imageExts = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']
	const ext = fileName.split('.').pop()?.toLowerCase() || ''
	return imageExts.includes(ext)
}

// 获取图片URL
const getImageUrl = (file: any) => {
	return file.thumbUrl || file.url || file.uploadData?.thumbUrl || file.uploadData?.url || file
}

// 预览图片
const previewImage = (file: any) => {
	const urls = formData.value.attachments
		.filter(f => isImageFile(f.name))
		.map(f => getImageUrl(f))
	
	uni.previewImage({
		current: getImageUrl(file),
		urls: urls
	})
}

// 预览文件
const previewFile = (file: any) => {
	uni.showToast({
		title: '该文件类型不支持预览',
		icon: 'none'
	})
}

// 格式化文件大小
const formatFileSize = (bytes: number) => {
	if (bytes === 0) return '0 B'
	const k = 1024
	const sizes = ['B', 'KB', 'MB', 'GB']
	const i = Math.floor(Math.log(bytes) / Math.log(k))
	return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 上傳附件
const chooseFile = async () => {
	uni.showActionSheet({
		itemList: ['选择图片', '拍照'],
		success: async (res) => {
			try {
				if (res.tapIndex === 0) {
					// 选择图片
					const chooseRes = await uni.chooseImage({
						count: 9,
						sizeType: ['compressed'],
						sourceType: ['album']
					})
					
					// 上傳選中的圖片
					for (let i = 0; i < chooseRes.tempFilePaths.length; i++) {
						const filePath = chooseRes.tempFilePaths[i]
						await uploadSingleFile(filePath)
					}
					
					uni.showToast({
						title: `已选择${chooseRes.tempFilePaths.length}张图片`,
						icon: 'success'
					})
				} else {
					// 拍照
					const chooseRes = await uni.chooseImage({
						count: 1,
						sizeType: ['compressed'],
						sourceType: ['camera']
					})
					
					// 上傳拍照的圖片
					for (let i = 0; i < chooseRes.tempFilePaths.length; i++) {
						const filePath = chooseRes.tempFilePaths[i]
						await uploadSingleFile(filePath)
					}
					
					uni.showToast({
						title: '拍照成功',
						icon: 'success'
					})
				}
			} catch (error) {
				console.error('选择图片失败:', error)
				uni.showToast({
					title: '选择图片失败',
					icon: 'none'
				})
			}
		}
	})
}

// 上传单个文件
const uploadSingleFile = async (filePath: string) => {
	try {
		const response = await uploadApi.uploadFile(filePath)
		if (response.code === 200) {
			// 从文件路径中提取文件名
			const fileName = filePath.split('/').pop() || `图片${formData.value.attachments.length + 1}`
			
			// 获取文件扩展名
			const fileExt = fileName.split('.').pop()?.toLowerCase() || ''
			
			// 构造附件对象，与编辑模式下的格式保持一致
			const attachment = {
				name: fileName,
				url: response.data?.url || filePath, // 如果没有url，使用本地路径
				thumbUrl: response.data?.thumbUrl || filePath, // 如果没有缩略图，使用原图
				fileSize: response.data?.fileSize || 0,
				fileExtension: fileExt,
				fileVersionId: response.data?.fileVersionId || null,
				uploadData: response.data, // 保存上传返回的数据，用于提交表单
				isTemp: true // 标记为临时文件，用于本地显示
			}
			
			formData.value.attachments.push(attachment)
			
			console.log('上传成功，附件对象:', attachment)
			console.log('当前附件列表:', formData.value.attachments)
		} else {
			throw new Error(response.msg || '上传失败')
		}
	} catch (error) {
		console.error('上传图片失败:', error)
		uni.showToast({
			title: '上传失败',
			icon: 'none'
		})
	}
}

// 删除附件
const deleteFile = (index: number) => {
	uni.showModal({
		title: '确认删除',
		content: '确定要删除这个附件吗？',
		success: (res) => {
			if (res.confirm) {
				formData.value.attachments.splice(index, 1)
				uni.showToast({
					title: '删除成功',
					icon: 'success'
				})
			}
		}
	})
}

const submitForm = async () => {
	if (!formData.value.planDate) {
		uni.showToast({ title: '请选择计划离职日期', icon: 'none' })
		return
	}
	
	if (!formData.value.regularWorkType) {
		uni.showToast({ title: '请选择离职类型', icon: 'none' })
		return
	}

	try {
		uni.showLoading({ title: '提交中...' })
		
		const openId = userStore.getOpenId()
		if (!openId) {
			uni.hideLoading()
			uni.showToast({ title: '请先登录', icon: 'none' })
			return
		}

		const submitData = {
			openId: openId,
			id: pageParams.value.id,
			planDate: formData.value.planDate,
			regularWorkType: formData.value.regularWorkType,
			regularReason: formData.value.regularReason
		}
		
		// 如果有附件，添加附件数据
		if (formData.value.attachments.length > 0) {
			// 构造附件数据，与编辑模式下的格式保持一致
			const attachmentData = formData.value.attachments.map(file => ({
				name: file.name,
				url: file.url || file.uploadData?.url || '',
				thumbUrl: file.thumbUrl || file.uploadData?.thumbUrl || '',
				fileSize: file.fileSize || file.uploadData?.fileSize || 0,
				fileExtension: file.fileExtension || file.uploadData?.fileExtension || '',
				fileVersionId: file.fileVersionId || file.uploadData?.fileVersionId || null
			}))
			
			// 使用嵌套数组格式，与编辑模式保持一致
			submitData.attachments = JSON.stringify([attachmentData])
			
			console.log('提交的附件数据:', submitData.attachments)
		}

		const response = await resignApi.updateResign(submitData)
		uni.hideLoading()

		if (response.code === 200) {
			uni.showToast({ title: '修改成功', icon: 'success' })
			setTimeout(() => { uni.navigateBack() }, 1500)
		} else {
			uni.showToast({ title: response.msg || '操作失败', icon: 'none' })
		}
	} catch (error) {
		uni.hideLoading()
		console.error('提交失败:', error)
		uni.showToast({ title: '网络错误', icon: 'none' })
	}
}

const goBack = () => { uni.navigateBack() }
</script>

<style lang="scss" scoped>
.edit-resign-page {
	background-color: #F5F5F5;
	min-height: 100vh;
	padding-bottom: calc(120rpx + env(safe-area-inset-bottom));
}

.form-content {
	padding: 20rpx;
}

.form-section {
	background-color: #FFFFFF;
	border-radius: 12rpx;
	margin-bottom: 20rpx;
	padding: 20rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.section-header {
	margin-bottom: 20rpx;
}

.section-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333333;
}

.form-field {
	margin-bottom: 20rpx;
}

.field-label {
	display: block;
	font-size: 28rpx;
	color: #666666;
	margin-bottom: 10rpx;
	
	&.required::before {
		content: '*';
		color: #FF4757;
		margin-right: 4rpx;
	}
}

.select-field {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx;
	background-color: #FFFFFF;
	border: 1rpx solid #E0E0E0;
	border-radius: 8rpx;
	cursor: pointer;
	transition: all 0.3s ease;
	
	&:hover {
		border-color: #FF6B35;
	}
}

.select-text {
	font-size: 28rpx;
	color: #333333;
	flex: 1;
}

.select-arrow {
	font-size: 24rpx;
	color: #999999;
}

/* 图片上传 */
.upload-area {
	padding: 20rpx;
	background-color: #FFFFFF;
	border-radius: 8rpx;
	border: 1rpx solid #E0E0E0;
}

.attachments-list {
	display: flex;
	flex-direction: column;
	gap: 15rpx;
	margin-bottom: 15rpx;
}

.file-item {
	display: flex;
	align-items: center;
	padding: 15rpx;
	background-color: #F8F8F8;
	border-radius: 8rpx;
	border: 1rpx solid #E0E0E0;
	cursor: pointer;
	transition: all 0.2s ease;
	min-height: 80rpx; /* 确保最小高度 */
	
	&:hover {
		background-color: #F0F0F0;
		border-color: var(--u-primary);
	}
}

.file-thumbnail {
	width: 60rpx;
	height: 60rpx;
	border-radius: 6rpx;
	margin-right: 15rpx;
	flex-shrink: 0;
	object-fit: cover; /* 确保图片正确填充 */
	background-color: #F0F0F0; /* 添加背景色，防止透明图片看不到 */
}

.file-icon {
	width: 60rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	background-color: #E0E0E0;
	border-radius: 6rpx;
	margin-right: 15rpx;
	flex-shrink: 0;
}

.icon-text {
	font-size: 32rpx;
	color: #666666;
}

.file-info {
	flex: 1;
	display: flex;
	flex-direction: column;
	gap: 5rpx;
	min-width: 0; /* 允许flex子项收缩 */
}

.file-name {
	font-size: 28rpx;
	color: #333333;
	font-weight: 500;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
	max-width: 200rpx; /* 限制最大宽度，防止溢出 */
}

.file-size {
	font-size: 24rpx;
	color: #999999;
}

.delete-file {
	font-size: 36rpx;
	color: #FF4757;
	margin-left: 10rpx;
}

.no-attachments {
	display: flex;
	align-items: center;
	justify-content: center;
	background-color: #F0F0F0;
	border: 1rpx dashed #E0E0E0;
	border-radius: 8rpx;
	padding: 20rpx;
	font-size: 28rpx;
	color: #999999;
	margin-bottom: 15rpx;
}

.no-attachments-text {
	font-size: 28rpx;
}

.upload-placeholder {
	display: flex;
	align-items: center;
	justify-content: center;
	background-color: #FFFFFF;
	border: 2rpx dashed #E0E0E0;
	border-radius: 8rpx;
	padding: 20rpx;
	cursor: pointer;
	transition: all 0.2s ease;
	
	&:hover {
		background-color: #F8F8F8;
		border-color: var(--u-primary);
	}
}

.upload-icon {
	font-size: 32rpx;
	margin-right: 10rpx;
	color: #999999;
}

.upload-text {
	font-size: 28rpx;
	color: #999999;
}

.bottom-actions {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background-color: #FFFFFF;
	padding: 20rpx;
	padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
	border-top: 1rpx solid #F0F0F0;
	display: flex;
	gap: 20rpx;
}

.action-btn {
	flex: 1;
	padding: 20rpx 0;
	border-radius: 8rpx;
	border: none;
	font-size: 28rpx;
	font-weight: bold;
	cursor: pointer;
	transition: all 0.3s ease;
	
	&.cancel-btn {
		background-color: #F0F0F0;
		color: #333333;
		
		&:hover {
			background-color: #E0E0E0;
		}
	}
	
	&.submit-btn {
		background-color: #FF6B35;
		color: #FFFFFF;
		
		&:hover {
			background-color: #E55A2B;
		}
	}
}

.type-picker {
	background-color: #FFFFFF;
	border-radius: 20rpx 20rpx 0 0;
	overflow: hidden;
}

.picker-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 30rpx;
	border-bottom: 1rpx solid #F0F0F0;
}

.picker-cancel {
	font-size: 28rpx;
	color: #666666;
	cursor: pointer;
}

.picker-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333333;
}

.picker-confirm {
	font-size: 28rpx;
	color: #007AFF;
	cursor: pointer;
}

.picker-content {
	max-height: 600rpx;
	overflow-y: auto;
}

.type-option {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 30rpx;
	border-bottom: 1rpx solid #F0F0F0;
	cursor: pointer;
	transition: all 0.3s ease;
	
	&:hover {
		background-color: #F8F8F8;
	}
	
	&.selected {
		background-color: #F0F8FF;
	}
}

.type-text {
	font-size: 28rpx;
	color: #333333;
}

.type-check {
	font-size: 24rpx;
	color: #007AFF;
	font-weight: bold;
}
</style>
